package com.gupao.rpc.protocol.client;

import com.gupao.rpc.protocol.protocol.RpcProtocol;
import com.gupao.rpc.protocol.protocol.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * netty客户端
 *
 * @author SuperWein
 */
@Slf4j
public class NettyClient {
    /**
     * 主机
     */
    private final String host;
    /**
     * 端口号
     */
    private final int port;

    private Bootstrap bootstrap;
    private EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());
    }

    public void sendRequest(RpcProtocol<RpcRequest> protocol) throws InterruptedException {
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        channelFuture.addListener(listener -> {
            if (listener.isSuccess()) {
                log.info("------->>>> connect rpc server {} success.", this.host);
            } else {
                log.info("------->>>> connect rpc server {} failed.", this.host);
                channelFuture.cause().printStackTrace();
                eventLoopGroup.shutdownGracefully();
            }
        });
        log.info("------->>>> begin to transfer data");
        channelFuture.channel().writeAndFlush(protocol);
    }

}
